/* tiff.c
 * This file is part of Landmerge (http://code.google.com/p/landmerge/)
 * Copyright (c) Matus Tejiscak 2008
 * Covered by GNU GPL v3 (http://www.gnu.org/licenses/gpl.txt).
 */

#include "tiff.h"
#include "stdlib.h"

tiff_t *tiff_open_r(const char *filename)
{
	TIFF* tif = TIFFOpen(filename, "r");
	if (!tif) return NULL;

	uint32 imagelength;
	tdata_t buf;
	uint32 row_size = TIFFScanlineSize(tif);

	TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imagelength);
	buf = _TIFFmalloc(row_size);
	if (!buf) return NULL;

	tiff_t *tiff = (tiff_t *) malloc(sizeof(tiff_t));
	if (!tiff)
	{
		_TIFFfree(buf);
		return NULL;
	}

	tiff->tiff = tif;
	tiff->scanline = buf;
	tiff->row_count = imagelength;
	tiff->cur_row = -1;
	tiff->row_size = row_size;

	tiff_next_scanline(tiff);

	return tiff;
}

void tiff_seek(tiff_t *tiff, unsigned row)
{
	if (!tiff) return;
	if (row >= tiff->row_count) return;

	tiff->cur_row = row;
	TIFFReadScanline(tiff->tiff, tiff->scanline, tiff->cur_row, 0);
}
void tiff_next_scanline(tiff_t *tiff)
{
	tiff_seek(tiff, tiff->cur_row + 1);
}

int tiff_eof(tiff_t *tiff)
{
	if (!tiff) return 1;

	return tiff->cur_row >= tiff->row_count-1;
}

void tiff_close(tiff_t *tiff)
{
	if (!tiff) return;

	_TIFFfree(tiff->scanline);
	TIFFClose(tiff->tiff);
	free(tiff);
}
